'use strict';

module.exports = app => {
  const db_table_name = 'hk_user';
  class UserService extends app.Service {
    async recortIsExist(kv) {
      const reslut = await app.mysql.get(db_table_name, kv);
      return !!reslut;
    }

    async unameIsUsed(uname) {
      return this.recortIsExist({ uname });
    }

    async uemailIsUsed(uemail) {
      return this.recortIsExist({ uemail });
    }

    async utellIsUsed(utel) {
      return this.recortIsExist({ utel });
    }

    async isUsed({ uid, uname, uemail, utel }) {
      const reslut = await app.mysql.query(`select * from ${db_table_name} where uid = ? or uname = ? or uemail = ? or utel = ?`, [ uid, uname, uemail, utel ]);
      return !!reslut.length;
    }

    async create({ uname, upassword, uemail, utel }) {
      if (!await this.isUsed({ uname, uemail, utel })) {
        const reslut = await app.mysql.insert(db_table_name, { uname, upassword, uemail, utel });
        return !!reslut;
      } return false;
    }

    async delete({ uid, uname, uemail, utel }) {
      if (await this.isUsed({ uid, uname, uemail, utel })) {
        const reslut = await app.mysql.query(`delete from ${db_table_name} where uid = ? or uname = ? or uemail = ? or utel = ?`, [ uid, uname, uemail, utel ]);
        return !!reslut;
      }
      return false;
    }

  }
  return UserService;
};
